import type {AxiosRequestConfig} from "axios";
import axios from "axios";
import {showFailToast} from "vant";
import router from "@/router";

export function request(config: AxiosRequestConfig<any>): Promise<any> {
    const instance = axios.create({
        baseURL: "https://api.shop.eduwork.cn",
        timeout: 5000,
        method: "get"
    });
    instance.interceptors.request.use(function (config) {
        const token = window.localStorage.getItem("token");
        if (token) {
            // 如果token存在
            // Authorization: Bearer Token ; key : value
            // 在headers头部加上Authorization属性，把token带到服务器里面
            config.headers.Authorization = "Bearer " + token; // Bearer 右边有一个空格
        }
        return config;
    }, function (error) {
        return Promise.reject(error);
    });
    instance.interceptors.response.use(res => {
        return res.data ? res.data : res;
    }, err => {
        if (err.code === "ERR_NETWORK" ||
            err.code === "ECONNABORTED") {
            showFailToast("网络错误!");
            return;
        }
        if (err.response && err.response.status === 401) {
            router.push({path: "/login"}).then(r => console.log(r));
        } else {
            // 如果后端接口有错误提示消息，这里统一处理,显示错误信息
            console.log(err);
            // 通过err.response响应数据里面的错误，拿到Object键里面的错误信息
            if (err.response && err.response.data && err.response.data.errors && err.response.data.errors.length > 0) {
                showFailToast(err.response.data.errors[Object.keys(err.response.data.errors)[0]][0]);
            }
        }
        return Promise.reject(err);
    });
    return instance(config);
}

